package com.minelx.sequence.pattern;

import com.minelx.sequence.core.*;

import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class JoinedEnumerationsMatcher implements ReturnMatcher<ReturnMatcher<?, StringScanner>, StringScanner> {

	private final JoinMatcher<ReturnMatcher<?, StringScanner>> enumerationsMatcher;

	public JoinedEnumerationsMatcher(ReturnMatcher<ReturnMatcher<?, StringScanner>, StringScanner> unitMatcher) {
		enumerationsMatcher = new JoinMatcher<>(Match.content(", "), unitMatcher);
	}

	@Override
	public boolean isMatch(StringScanner clue) {
		return clue.exists("(");
	}

	@Override
	public ReturnMatcher<?, StringScanner> onMatched(StringScanner clue) {
		clue.goes("(");
		List<ReturnMatcher<?, StringScanner>> enumerations = enumerationsMatcher.get(clue).orElseThrow(RuntimeException::new);
		clue.goes(")");
		OrMatcher<?, StringScanner> allEnumerations = OrMatcher.create(enumerations);
		return ReturnMatcher.create(
				allEnumerations::isMatch,
				scanner -> scanner.stream(allEnumerations).map(Object::toString).collect(joining())
		);
	}
}
